package com.cdk8s.tkey.server.controller;

import com.cdk8s.tkey.server.constant.GlobalVariable;
import com.cdk8s.tkey.server.pojo.bo.cache.OauthClientToRedisBO;
import com.cdk8s.tkey.server.pojo.dto.client.OauthClientCreateRequestParam;
import com.cdk8s.tkey.server.pojo.dto.resp.R;
import com.cdk8s.tkey.server.service.OauthClientService;
import com.cdk8s.tkey.server.util.JsonUtil;
import com.cdk8s.tkey.server.util.redis.StringRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author zhang
 */
@Slf4j
@RestController
@RequestMapping("/client")
public class ClientController {
	@Autowired
	private StringRedisService<String, String> clientRedisService;

	@Autowired
	private OauthClientService oauthClientService;

	@PostMapping("/save")
	public ResponseEntity<?> save(@RequestBody @Valid OauthClientCreateRequestParam param) {
		OauthClientToRedisBO oauthClientToRedisBO = new OauthClientToRedisBO();
		BeanUtils.copyProperties(param, oauthClientToRedisBO);
		clientRedisService.set(GlobalVariable.REDIS_CLIENT_ID_KEY_PREFIX + oauthClientToRedisBO.getClientId(), JsonUtil.toJson(oauthClientToRedisBO));
		return R.success(oauthClientToRedisBO);
	}

	@GetMapping("/query")
	private ResponseEntity<?> query(@RequestParam String clientId) {
		return R.success(oauthClientService.findByClientId(clientId));
	}

	@GetMapping("/delete")
	private ResponseEntity<?> delete(@RequestParam String clientId) {
		String clientIdRedisKey = GlobalVariable.REDIS_CLIENT_ID_KEY_PREFIX + clientId;
		clientRedisService.delete(clientIdRedisKey);
		return R.success();
	}
}
